from ferris import BasicModel
from google.appengine.ext import ndb
from app.models import util
from app.models.feature import Feature


class Column(BasicModel):
    """
    Models columns appearing regularly in a particular publication.
    """
    publication = ndb.KeyProperty(kind="Publication", required=True)
    name = ndb.StringProperty(required=True)
    name_sort = ndb.ComputedProperty(lambda self:
                                     util.homogenize_name(self.name))
    search_terms = ndb.ComputedProperty(lambda self:
                                        util.create_search_terms(self.name),
                                        repeated=True)

    @classmethod
    def list_query(cls, query=None):
        """
        Queries all columns with an optional query string, ordered
        alphabetically.
        """
        if query:
            search_args = util.prepare_search_args(query)
            results = cls.query(cls.search_terms.IN(search_args))
        else:
            results = cls.query()

        return results.order(cls.name_sort, cls.key)

    def all_features(self):
        """
        List all features of a column.
        """
        return Feature.query(Feature.column == self.key).order(
            -Feature.publication_day)
